﻿using System.Configuration;
using System.Linq;
using Testing.Helpers.Assertion;

namespace Testing.Helpers.Confiuration
{
    /// <summary>
    /// Manager for work with config file for class library project type.
    /// </summary>
    public class ConfigFileManager
    {
        private readonly KeyValueConfigurationCollection _appSettings;
        private readonly Configuration _appConfiguration;
        
        /// <summary>
        /// Initializes a new instance of the <see cref="T:Testing.Helpers.Confiuration.ConfigFileManager"/> class.
        /// </summary>
        /// <param name="configFilePath">Config file full path.</param>
        /// <param name="userLevel">UserLevel.</param>
        public ConfigFileManager(string configFilePath, ConfigurationUserLevel userLevel)
        {
            var map = new ExeConfigurationFileMap {ExeConfigFilename = configFilePath};
            _appConfiguration = ConfigurationManager.OpenMappedExeConfiguration(map, userLevel);
            _appSettings = _appConfiguration.AppSettings.Settings;
        } 

        /// <summary>
        /// Initializes a new instance of the <see cref="T:Testing.Helpers.Confiuration.ConfigFileManager"/> class.
        /// </summary>
        /// <param name="exePath">Full path to application.</param>
        public ConfigFileManager(string exePath)
        {
            Configuration appConfiguration = ConfigurationManager.OpenExeConfiguration(exePath);
            AppSettingsSection appSettings = appConfiguration.AppSettings;
            _appSettings = appSettings.Settings;
        }

        /// <summary>
        /// Gets the setting value for appSettings section.
        /// </summary>
        /// <param name="key">Setting key.</param>
        /// <returns>Setting value.</returns>
        public string GetAppSettingValue(string key)
        {
            string message = "Failed to find setting key - " + key + " - in config file.";
           
            if (!_appSettings.AllKeys.Contains(key))
            {
                throw new TestExecutionException(message);
            }

            return _appSettings[key].Value;
        }


        /// <summary>
        /// Sets the setting value for appSettings section.
        /// </summary>
        /// <param name="key">Setting key.</param>
        /// <param name="value">Setting value.</param>
        public void SetAppSettingValue(string key, string value)
        {
            string message = "Failed to find setting key - " + key + " - in config file.";
            if (!_appSettings.AllKeys.Contains(key))
            {
                throw new TestExecutionException(message);
            }
            _appSettings[key].Value = value;
            _appConfiguration.Save(ConfigurationSaveMode.Minimal);
        }
    }
}
